using System.Text;
using RSCore.Files;

namespace RSCore;

public class KeyConverter144 : KeyConverter
{
	public KeyConverter144()
	{
		_sb = new StringBuilder(32);
		_entryTypeMapping = new()
		{
			["Items"] = EntryType.Item,
			["Projectiles"] = EntryType.Projectile,
			["NPCs"] = EntryType.NPC,
			["Buffs"] = EntryType.Buff,
			["Tiles"] = EntryType.Tile,
			["TownNPCMood"] = EntryType.TownNPCMood,
			["Prefixes"] = EntryType.Prefix,
			["Biomes"] = EntryType.Biome,
			["InfoDisplays"] = EntryType.InfoDisplay,
			["DamageClasses"] = EntryType.DamageClass,
		};
		_reverseEntryTypeMapping = _entryTypeMapping.ToDictionary(
			p => p.Value,
			p => p.Key);
	}

	public override KeyData Convert(string key)
	{
		key = Normalize(key);
		var match = SplitKey(key);
		if (match.Success && _entryTypeMapping.TryGetValue(match.Groups[1].Value, out var entry))
		{
			var property = match.Groups[3].Value;

			Type type = entry.GetFileType();
			if (type.HasProperty(property) || type.IsAssignableTo(typeof(IExtensibleFile)))
			{
				return new KeyData(match.Groups[2].Value, entry, property);
			}
		}
		return new KeyData(key, EntryType.None, string.Empty);
	}

	public override string Convert(KeyData key)
	{
		if (key.EntryType == EntryType.None)
		{
			return key.Identity;
		}

		return _sb.Clear().Append(_reverseEntryTypeMapping[key.EntryType]).Append('.')
				.Append(key.Identity).Append('.')
				.Append(key.Property)
				.ToString();
	}

	private readonly Dictionary<string, EntryType> _entryTypeMapping;

	private readonly Dictionary<EntryType, string> _reverseEntryTypeMapping;

	private StringBuilder _sb;
}